package com.spoto.oa.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import com.oreilly.servlet.MultipartRequest;
import com.spoto.oa.model.Employee;
import com.spoto.oa.service.EmployeeServ;
import com.spoto.oa.service.impl.EmployeeServImpl;
import com.spoto.oa.util.RandomFileRenamePolicy;
import com.spoto.oa.util.DateUtil;

/**
 * 
 * @project: OA_Beta
 * @description: 员工管理
 * @date：2010-11-18~2010-11-18
 * @author: LinYiSong
 *
 */
public class EmployeeServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public EmployeeServlet() {
		super();
	}

	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Employee employee = new Employee();
		EmployeeServ employeeServ = new EmployeeServImpl();
		String type = request.getParameter("op_type");
		List<Employee> confictEmployees = new ArrayList<Employee>();
		if ("search".equals(type)) {
			List<Employee> employees = null;
			String searchType = request.getParameter("searchType");
			String infor = request.getParameter("infor");
			if ("员工帐号".equals(searchType)) {
				employees = employeeServ.searchByUserName(infor);

			} else if ("员工姓名".equals(searchType)) {
				employees = employeeServ.searchByName(infor);
			}
			request.setAttribute("employees", employees);
			request.setAttribute("infor", infor);
			request.setAttribute("searchType", searchType);
			request.getRequestDispatcher("/employee/welcome_employee.jsp")
					.forward(request, response);
		} else if ("add".equals(type)) {
			employee.setName(request.getParameter("name"));// 根据jsp页面中的name属性取值
			employee.setUsername(request.getParameter("username"));
			employee.setSex(request.getParameter("sex"));
			employee.setIsAdmin(request.getParameter("isAdmin"));
			employee.setBirth(DateUtil.parseToDate(request
					.getParameter("birth")));
			employee.setEmail(request.getParameter("email"));
			employee.setCell(request.getParameter("cell"));
			employee.setDateIn(DateUtil.parseToDate(request
					.getParameter("dateIn")));
			employee.setAge(DateUtil.parseToInt(request.getParameter("age")));
			employee.setQq(request.getParameter("qq"));
			employee.setMsn(request.getParameter("msn"));
			employee.setSchool(request.getParameter("school"));
			employee.setAddress(request.getParameter("address"));
			employee.setSelf(request.getParameter("self"));
			try {
				employeeServ.addEmployee(employee);
			} catch (SQLException e) {

			}
			List<Employee> employees = null;
			employees = employeeServ.getAllEmployees();
			request.setAttribute("employees", employees);
			request.getRequestDispatcher(
					"/employee/welcome_employee.jsp?op_type=to_edit").forward(
					request, response);
		} else if ("delete".equals(type)) {
			String username = request.getParameter("username");
			List<Employee> employees = employeeServ.searchByUserName(username);
			employeeServ.deleteEmployee(employees.get(0));

			response.setContentType("text/html");
			employees = employeeServ.getAllEmployees();
			request.setAttribute("employees", employees);
			request.getRequestDispatcher("/employee/welcome_employee.jsp?op_type=to_edit")
					.forward(request, response);
		} else if ("to_update".equals(type)) {
			String username = request.getParameter("username");
			List<Employee> employees = employeeServ.searchByUserName(username);
			request.setAttribute("employee", employees.get(0));
			request.getRequestDispatcher("/employee/update_employee.jsp")
					.forward(request, response);

		} else if ("update".equals(type)) {
			employee.setName(request.getParameter("name"));// 根据jsp页面中的name属性取值
			employee.setUsername(request.getParameter("username"));

			employee.setSex(request.getParameter("sex"));
			employee.setIsAdmin(request.getParameter("isAdmin"));
			employee.setBirth(DateUtil.parseToDate(request
					.getParameter("birth")));
			employee.setEmail(request.getParameter("email"));
			employee.setCell(request.getParameter("cell"));
			employee.setDateIn(DateUtil.parseToDate(request
					.getParameter("dateIn")));
			employee.setAge(DateUtil.parseToInt(request.getParameter("age")));
			employee.setQq(request.getParameter("qq"));
			employee.setMsn(request.getParameter("msn"));
			employee.setSchool(request.getParameter("school"));
			employee.setAddress(request.getParameter("address"));
			employee.setSelf(request.getParameter("self"));

			employeeServ.updateEmployee(employee);
			List<Employee> employees = null;
			employees = employeeServ.getAllEmployees();
			request.setAttribute("employees", employees);
			request.getRequestDispatcher("/employee/welcome_employee.jsp?op_type=to_edit")
					.forward(request, response);
		} else if ("upload".equals(type)) {
			// 存绝对路径
			// String filePath = "C://upload";
			// 存相对路径
			String filePath = "G:";
			File uploadPath = new File(filePath);
			// 检查文件夹是否存在 不存在 创建一个
			if (!uploadPath.exists()) {
				uploadPath.mkdir();
			}
			// 文件最大容量 5M
			int fileMaxSize = 5 * 1024 * 1024;
			// 存放文件描述
			String[] fileDiscription = { null, null };
			// 文件名
			String fileName = null;
			// 上传文件数
			int fileCount = 0;
			// 重命名策略
			RandomFileRenamePolicy rfrp = new RandomFileRenamePolicy();
			// 上传文件
			MultipartRequest mulit = new MultipartRequest(request, filePath,
					fileMaxSize, "utf-8", rfrp);
			filePath += rfrp.getFileName();

			// 将Excel文件读入数据库
			// 封装Employee
			InputStream inp = new FileInputStream(filePath);
			// InputStream inp = new FileInputStream("workbook.xlsx");

			HSSFWorkbook wb = new HSSFWorkbook(inp);// 可以看作是在虚拟下架构出一个workbook
			// 读取文件中的第一张表格
			HSSFSheet sheet = wb.getSheetAt(0);
			// 定义 row、cell
			HSSFRow row;
			// HSSFCell cell;
			String cell;
			// 循环输出表格中的内容
			for (int i = sheet.getFirstRowNum() + 1; i < sheet
					.getPhysicalNumberOfRows(); i++) {
				employee = new Employee();
				row = sheet.getRow(i);
				int j = row.getFirstCellNum();
				employee.setUsername(row.getCell(0 + j).toString());
				employee.setPassword(row.getCell(1 + j).toString());
				employee.setIsAdmin(row.getCell(2 + j).toString());
				employee.setAge((int) row.getCell(3 + j).getNumericCellValue());
				employee.setName(row.getCell(4 + j).toString());// 根据jsp页面中的name属性取值
				employee.setSex(row.getCell(5 + j).toString());
				employee.setBirth(new java.sql.Date(row.getCell(6 + j)
						.getDateCellValue().getTime()));
				employee.setDateIn(new java.sql.Date(row.getCell(7 + j)
						.getDateCellValue().getTime()));
				employee.setQq(String.format("%.0f", row.getCell(8 + j)
						.getNumericCellValue()));
				employee.setMsn(String.format("%.0f", row.getCell(9 + j)
						.getNumericCellValue()));
				employee.setCell(String.format("%.0f", row.getCell(10 + j)
						.getNumericCellValue()));
				employee.setSchool(row.getCell(11 + j).toString());
				employee.setEmail(row.getCell(12 + j).toString());
				employee.setPhone(String.format("%.0f", row.getCell(13 + j)
						.getNumericCellValue()));
				employee.setAddress(row.getCell(14 + j).toString());
				employee.setSelf(row.getCell(15 + j).toString());

				try {
					employeeServ.addEmployee(employee);
				} catch (SQLException e) {
					try {
						confictEmployees.add(employee);
						employeeServ.addEmployeeConfict(employee);
					} catch (SQLException e1) {
						e1.printStackTrace();
					}
				}
			}
			if (confictEmployees.size() != 0) {
				request.setAttribute("employees", confictEmployees);
				request.getRequestDispatcher(
						"/employee/list_confict_employee.jsp").forward(request,
						response);
			} else {
				List<Employee> employees = null;
				employees = employeeServ.getAllEmployees();
				request.setAttribute("employees", employees);
				request.getRequestDispatcher("/employee/welcome_employee.jsp")
						.forward(request, response);
			}

		} else if ("to_edit".equals(type)) {
			List<Employee> employees = null;
			employees = employeeServ.getAllEmployees();
			request.setAttribute("employees", employees);
			request.getRequestDispatcher("/employee/welcome_employee.jsp")
					.forward(request, response);
		} else if ("multi_del".equals(type)) {
			String[] delUserName = request.getParameterValues("del-flag");
			for (int i = 0; i < delUserName.length; i++) {
				employeeServ.deleteEmployeeByUsername(delUserName[i]);
			}

			List<Employee> employees = null;
			employees = employeeServ.getAllEmployees();
			request.setAttribute("employees", employees);
			request.getRequestDispatcher("/employee/welcome_employee.jsp?op_type=to_edit")
					.forward(request, response);

		} else if ("valicate".equals(type)) {// 进行异步验证
			String kind = request.getParameter("kind");
			if ("username".equals(kind)) {
				String username = request.getParameter("username");
				PrintWriter out = response.getWriter();
				if (null != employeeServ.getByUserName(username)) {
					out.write("false");
				} else {
					out.write("true");
				}
			} else if ("psw".equals(kind)) {
				String username = request.getParameter("username");
				String oldPsw = request.getParameter("old_psw");
				String psw = employeeServ.getByUserName(username).getPassword();
				PrintWriter out = response.getWriter();
				if (oldPsw.equals(psw)) {
					out.write("true");
				} else {
					out.write("false");
				}
			}
		} else if ("conflict".equals(type)) {// 处理导入员工数据时存在的冲突数据
			String kind = request.getParameter("conflict_op");
			if ("to_update".equals(kind)) {
				String username = request.getParameter("username");
				employee = employeeServ.getByUserNameConfict(username);
				employeeServ.updateEmployee(employee);
				employeeServ.deleteEmployeeConfict(employee);
				confictEmployees = employeeServ.getAllEmployeesConfict();
				request.setAttribute("employees", confictEmployees);
				request.getRequestDispatcher(
						"/employee/list_confict_employee.jsp?conflict_op=list").forward(request,
						response);
			} else if ("delete".equals(kind)) {
				String username = request.getParameter("username");
				employee = employeeServ.getByUserNameConfict(username);
				employeeServ.deleteEmployeeConfict(employee);
				confictEmployees = employeeServ.getAllEmployeesConfict();
				request.setAttribute("employees", confictEmployees);
				request.getRequestDispatcher(
						"/employee/list_confict_employee.jsp?conflict_op=list").forward(request,
						response);
			} else if ("multi_del".equals(kind)) {
				String[] delUserName = request.getParameterValues("del-flag");
				for (int i = 0; i < delUserName.length; i++) {
					Employee employeeDel = employeeServ
							.getByUserNameConfict(delUserName[i]);
					employeeServ.deleteEmployeeConfict(employeeDel);
				}
				List<Employee> employees = null;
				employees = employeeServ.getAllEmployeesConfict();
				request.setAttribute("employees", employees);
				request.getRequestDispatcher(
						"/employee/list_confict_employee.jsp?conflict_op=list").forward(request,
						response);
			}else if("list".equals(kind)){
				List<Employee> employees = null;
				employees = employeeServ.getAllEmployeesConfict();
				request.setAttribute("employees", employees);
				request.getRequestDispatcher(
						"/employee/list_confict_employee.jsp?conflict_op=list").forward(request,
						response);
			}
		} else if ("edit_psw".equals(type)) {
			String psw = request.getParameter("new_psw");
			String username = request.getParameter("username");
			System.out.println(username+psw);
			employeeServ.editPsw(username, psw);
			request.getRequestDispatcher("/employee/edit_psw_success.jsp")
					.forward(request, response);
		}
	}

	/**
	 * Initialization of the servlet. <br>
	 * 
	 * @throws ServletException
	 *             if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}
